package com.taokatao.cardmee.business.carddetail;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.taokatao.cardmee.App;
import com.taokatao.cardmee.BaseActivity;
import com.taokatao.cardmee.C;
import com.taokatao.cardmee.R;
import com.taokatao.cardmee.Utils;
import com.taokatao.cardmee.WebActivity;
import com.taokatao.cardmee.api.ApiManager;
import com.taokatao.cardmee.api.RespInfo;
import com.taokatao.cardmee.api.RespWrapper;
import com.taokatao.cardmee.api.SubscriberAdapter;
import com.taokatao.cardmee.api.model.CardFDMyCourseInfo;
import com.taokatao.cardmee.api.security.ServiceUrlProvider;
import com.taokatao.cardmee.db.model.Card;
import com.taokatao.cardmee.util.PtrHeaderHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.aigestudio.datepicker.cons.DPMode;
import cn.aigestudio.datepicker.views.DatePicker;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

public class CardFDBookActivity extends BaseActivity implements View.OnClickListener, CardFDBookDateLayout.Callback {
    @BindView(R.id.l_empty) View lEmpty;

    @BindView(R.id.l_card_fd_book_date) CardFDBookDateLayout lCardFDBookDate;
    @BindView(R.id.i_calendar) ImageView iCalendar;
    @BindView(R.id.v_recycler) RecyclerView vRecycler;
    @BindView(R.id.l_ptr_frame) PtrFrameLayout lPtrFrame;

    BookAdapter adapter;

    /**
     * yyyyMMdd 格式的时间
     */
    private String mSelectedDate;
    private AlertDialog dlgCalendar;

    Card c;
    List<CardFDMyCourseInfo> dataList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_fd_book);
        ButterKnife.bind(this);
        c = (Card) getIntent().getSerializableExtra("extra_card");

        vRecycler.setLayoutManager(new LinearLayoutManager(this));
        vRecycler.setHasFixedSize(true);
        vRecycler.setAdapter(adapter = new BookAdapter(c.getMCardId(), c.getSid()));

        PtrHeaderHelper.initDefault(this, lPtrFrame);
        lPtrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, vRecycler, header);
            }

            @Override
            public void onRefreshBegin(final PtrFrameLayout frame) {
                requestGetBranchCourseList(mSelectedDate, lCardFDBookDate.getSelectedDate(), "pullToRefresh");
            }
        });

        lCardFDBookDate.setCallback(this);
        lCardFDBookDate.setData(mSelectedDate = new SimpleDateFormat("yyyyMMdd").format(new Date()));

        // 初次请求显示Dialog
        requestGetBranchCourseList(mSelectedDate, mSelectedDate, "showProgress");
    }

    @Override
    public void onNewDateClick(String dateTime) {
        Utils.logd("onNewDateClick dateTime:" + dateTime + "#dataList.size:" + (dataList != null ? dataList.size() : -1));
        boolean isShownDayEmpty = adapter.set(dateTime, dataList);
        lEmpty.setVisibility(isShownDayEmpty ? View.VISIBLE : View.GONE);
    }

    private void requestGetBranchCourseList(final String requestDate, final String shownDate, String loadingType) {
        SubscriberAdapter subscriberAdapter = new SubscriberAdapter<RespWrapper<List<CardFDMyCourseInfo>>>() {
            @Override
            public void onNext(RespWrapper<List<CardFDMyCourseInfo>> o) {
                super.onNext(o);
                if (o.code == C.http.RESULT_CODE_SUCCESS) {
                    dataList = o.decode(new TypeToken<List<CardFDMyCourseInfo>>() {
                    }.getType());
                    boolean isShownDayEmpty = adapter.set(shownDate, dataList);
                    lEmpty.setVisibility(isShownDayEmpty ? View.VISIBLE : View.GONE);
                    lCardFDBookDate.refreshOrderFlag(dataList);
                }
            }
        };
        if ("showProgress".equals(loadingType)) {
            subscriberAdapter.showProgress(this);
        } else if ("pullToRefresh".equals(loadingType)) {
            subscriberAdapter.pullToRefresh(lPtrFrame);
        }
        ApiManager.i().getBranchCourseList(this, App.i().getCurrUser().getUuid(), c.getMCardId(), c.getSid(), requestDate, subscriberAdapter);
    }


    @Override
    @OnClick({R.id.i_calendar})
    public void onClick(View v) {
        if (v == iCalendar) {
            showCalendarDialog();
        }
    }

    private void showCalendarDialog() {
        if (dlgCalendar == null) {
            dlgCalendar = new AlertDialog.Builder(this).create();
        }
        dlgCalendar.show();
        DatePicker picker = new DatePicker(this);
        Calendar calendar = Calendar.getInstance();
        picker.setDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1);
        picker.setMode(DPMode.SINGLE);
        picker.setOnDatePickedListener(new DatePicker.OnDatePickedListener() {
            @Override
            public void onDatePicked(String date) {
                dlgCalendar.dismiss();
                try {
                    int year = Integer.parseInt(date.split("-")[0]);
                    int month = Integer.parseInt(date.split("-")[1]);
                    int day = Integer.parseInt(date.split("-")[2]);
                    String sMonth = (month < 10 ? "0" : "") + month;
                    String sDay = (day < 10 ? "0" : "") + day;
                    String dateValue = year + sMonth + sDay;
                    lCardFDBookDate.setData(mSelectedDate = dateValue);
                    requestGetBranchCourseList(mSelectedDate, mSelectedDate, "showProgress");
                } catch (Exception e) {
                    e.printStackTrace();
                    Utils.showToast("日历选择日期结果异常");
                }
            }
        });
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dlgCalendar.getWindow().setContentView(picker, params);
        dlgCalendar.getWindow().setGravity(Gravity.CENTER);
    }


    static class BookAdapter extends RecyclerView.Adapter {
        final int STATE_NONE = 0;
        final int STATE_ORDER = 1;
        final int STATE_AFTER_ORDER = 2;
        final int STATE_ORDER_CANCEL = 3;
        final int STATE_AFTER_ORDER_CANCEL = 4;
        final List<CardFDMyCourseInfo> dataList = new ArrayList<>();
        long mCardId, mSid;

        BookAdapter(long cardId, long sid) {
            mCardId = cardId;
            mSid = sid;
        }

        /**
         * 返回当天数据是否为空
         */
        public boolean set(String currDate, List<CardFDMyCourseInfo> list) {
            boolean isShownDayEmpty = true;
            dataList.clear();
            if (list != null) {
                try {
                    for (CardFDMyCourseInfo cci : list) {
                        if (String.valueOf(cci.classTime).startsWith(currDate)) {
                            // 添加当天的
                            dataList.add(cci);
                            isShownDayEmpty = false;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            notifyDataSetChanged();
            return isShownDayEmpty;
        }

        class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            TextView tCourseName, tTime, tTeacherName, tCoursePerimeter;
            ImageView iLogo;

            TextView tState1;
            View lState2;
            TextView tState2, tStateCount2;
            View lState3;
            TextView tState3, tState3Tip;


            /**
             * 类型 1预约;2候补预约 必填
             */
            int mItemState;
            CardFDMyCourseInfo cci;

            ViewHolder(View itemView) {
                super(itemView);
                tCourseName = (TextView) itemView.findViewById(R.id.t_course_name);
                tTime = (TextView) itemView.findViewById(R.id.t_time);
                iLogo = (ImageView) itemView.findViewById(R.id.i_logo);
                tTeacherName = (TextView) itemView.findViewById(R.id.t_teacher_name);
                tCoursePerimeter = (TextView) itemView.findViewById(R.id.t_course_perimeter);

                tState1 = (TextView) itemView.findViewById(R.id.t_state_1);
                tState1.setOnClickListener(this);
                lState2 = itemView.findViewById(R.id.l_state_2);
                tState2 = (TextView) itemView.findViewById(R.id.t_state_2);
                tStateCount2 = (TextView) itemView.findViewById(R.id.t_state_count_2);
                lState2.setOnClickListener(this);
                lState3 = itemView.findViewById(R.id.l_state_3);
                tState3 = (TextView) itemView.findViewById(R.id.t_state_3);
                tState3.setOnClickListener(this);
                tState3Tip = (TextView) itemView.findViewById(R.id.t_state_3_tip);

                itemView.setOnClickListener(this);
            }

            void refresh(CardFDMyCourseInfo data) {
                cci = data;
                if (cci == null) {
                    itemView.setVisibility(View.GONE);
                } else {
                    mItemState = STATE_NONE;
                    itemView.setVisibility(View.VISIBLE);
                    tCourseName.setText(cci.courseName);
                    tTime.setText(formatTime(cci.classTime));
                    Glide.with(itemView.getContext()).load(cci.coursePic)
                            .placeholder(R.mipmap.card_fd_course_default).bitmapTransform(App.i().getRoundedCornersTransformation()).into(iLogo);
                    tTeacherName.setText(cci.teacherName);
                    tCoursePerimeter.setText(cci.coursePerimeter + "课时");


                    if (cci.status == CardFDMyCourseInfo.STATUS_ORDERED && cci.ifCancelBook == CardFDMyCourseInfo.BOOK_CANCEL_ABLE) {
                        tState1.setVisibility(View.GONE);
                        lState2.setVisibility(View.GONE);
                        lState3.setVisibility(View.VISIBLE);
                        tState3.setText("取消预约");
                        tState3Tip.setText("已预约");
                        mItemState = STATE_ORDER_CANCEL;
                    } else if (cci.status == CardFDMyCourseInfo.STATUS_AFTER) {
                        tState1.setVisibility(View.GONE);
                        lState2.setVisibility(View.GONE);
                        lState3.setVisibility(View.VISIBLE);
                        tState3.setText("取消候补");
                        tState3Tip.setText("已候补");
                        mItemState = STATE_AFTER_ORDER_CANCEL;
                    } else if (cci.status == CardFDMyCourseInfo.STATUS_ORDERED) {
                        tState1.setVisibility(View.VISIBLE);
                        lState2.setVisibility(View.GONE);
                        lState3.setVisibility(View.GONE);
                        tState1.setTextColor(0xFF10742A);
                        tState1.setText("已预约");
                    } else if (cci.ifOpenBook == CardFDMyCourseInfo.ORDER_BOOK_DISABLE) {
                        tState1.setVisibility(View.VISIBLE);
                        lState2.setVisibility(View.GONE);
                        lState3.setVisibility(View.GONE);
                        tState1.setTextColor(0xFF888888);
                        tState1.setText("未开放预约");
                    } else if (cci.allPeopleNum - cci.confirmClassNum > 0) {
                        tState1.setVisibility(View.GONE);
                        lState2.setVisibility(View.VISIBLE);
                        lState3.setVisibility(View.GONE);
                        lState2.setBackgroundColor(0xFFFE356D);
                        tState2.setText("预约");
                        tStateCount2.setText(cci.confirmClassNum + "人报名");
                        mItemState = STATE_ORDER;
                    } else if (cci.ifAfter == CardFDMyCourseInfo.AFTER_ABLE
                            && cci.afterNum - cci.afterBookNum > 0) {
                        tState1.setVisibility(View.GONE);
                        lState2.setVisibility(View.VISIBLE);
                        lState3.setVisibility(View.GONE);
                        lState2.setBackgroundColor(0xFF688EEF);
                        tState2.setText("候补预约");
                        tStateCount2.setText(cci.afterBookNum + "人报名");
                        mItemState = STATE_AFTER_ORDER;
                    } else {
                        tState1.setVisibility(View.VISIBLE);
                        lState2.setVisibility(View.GONE);
                        lState3.setVisibility(View.GONE);
                        tState1.setTextColor(0xFF98042D);
                        tState1.setText("已满");
                    }
                }
            }

            @Override
            public void onClick(View v) {
                if (v == tState1 || v == lState2 || v == tState3) {
                    if (mItemState != STATE_NONE) {
                        if (mItemState == STATE_ORDER
                                && cci.ifBook == CardFDMyCourseInfo.BOOK_ABLE) {
                            showTipsDialog();
                        } else {
                            requestOrderBranchCourse(this);
                        }
                    }
                } else  if (v == itemView) {
                    Intent intent = new Intent(v.getContext(), WebActivity.class);
                    // 这里的cci.courseId 取不到 课程id， 用 cci.id 取值
                    intent.putExtra("extra_url", ServiceUrlProvider.obtainOrderedCourseDetailsUrl(cci.id , 2));
                    v.getContext().startActivity(intent);
                }
            }

            com.taokatao.cardmee.common.widget.AlertDialog dlgTips;

            void showTipsDialog() {
                if (dlgTips == null) {
                    dlgTips = new com.taokatao.cardmee.common.widget.AlertDialog.Builder(itemView.getContext())
                            .setTitle("提示").setMessage("课程预约成功后，会预先扣除课程剩余次数，是否仍要继续进行预约操作？")
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).setPositiveButton("继续", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    requestOrderBranchCourse(ViewHolder.this);
                                }
                            }).create();
                }
                dlgTips.show();
            }
        }

        SimpleDateFormat parser = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");

        String formatTime(long timestamp) {
            String sTimestamp = String.valueOf(timestamp);
            if (sTimestamp.length() != 14) return "";
            String result = "";
            try {
                Date date = parser.parse(sTimestamp);
                result = formatter.format(date);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                return result;
            }
        }

        /**
         * 预约请求 或者 候补请求 或者 取消预约  或者 取消候补 根据[mItemState]判断
         *
         * @param viewHolder
         */
        void requestOrderBranchCourse(final ViewHolder viewHolder) {
            final int mState = viewHolder.mItemState;
            final CardFDMyCourseInfo cci = viewHolder.cci;
            ApiManager.i().orderBranchCourse(viewHolder.itemView.getContext(),
                    App.i().getCurrUser().getUuid(), mCardId, mSid, viewHolder.cci.id, mState, new SubscriberAdapter<RespWrapper<RespInfo>>() {
                        @Override
                        public void onNext(RespWrapper<RespInfo> o) {
                            super.onNext(o);
                            if (o.code == C.http.RESULT_CODE_SUCCESS) {
                                if (mState == STATE_AFTER_ORDER) {
                                    cci.status = CardFDMyCourseInfo.STATUS_AFTER;
                                } else if (mState == STATE_ORDER) {
                                    cci.status = CardFDMyCourseInfo.STATUS_ORDERED;
                                } else {
                                    cci.status = CardFDMyCourseInfo.STATUS_NONE;
                                }

                                if (mState == STATE_ORDER) {
                                    cci.confirmClassNum = cci.confirmClassNum + 1;
                                } else if (mState == STATE_AFTER_ORDER) {
                                    cci.afterBookNum = cci.afterBookNum + 1;
                                } else if (mState == STATE_ORDER_CANCEL) {
                                    cci.confirmClassNum = cci.confirmClassNum - 1;
                                } else if (mState == STATE_AFTER_ORDER_CANCEL) {
                                    cci.afterBookNum = cci.afterBookNum - 1;
                                }

                                viewHolder.refresh(cci);
                            }
                        }
                    }.showProgress(viewHolder.itemView.getContext()));
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_card_fd_book, parent, false));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            ((ViewHolder) holder).refresh(dataList.get(position));
        }

        @Override
        public int getItemCount() {
            return dataList.size();
        }
    }
}
